from flask import Blueprint, request, jsonify, send_file
from flask_jwt_extended import jwt_required, get_jwt_identity
from controllers.recording_controller import RecordingController

recordings_bp = Blueprint('recordings', __name__)

@recordings_bp.route('/user', methods=['GET'])
@jwt_required()
def get_user_recordings():
    current_user = get_jwt_identity()
    user_id = int(current_user)
    result = RecordingController.get_user_recordings(user_id)
    return jsonify(result)

@recordings_bp.route('/stats', methods=['GET'])
@jwt_required()
def get_user_stats():
    current_user = get_jwt_identity()
    user_id = int(current_user)
    result = RecordingController.get_user_stats(user_id)
    return jsonify(result)

@recordings_bp.route('', methods=['POST'])
@jwt_required()
def upload_recording():
    current_user = get_jwt_identity()
    user_id = int(current_user)
    
    if 'audio_file' not in request.files:
        return jsonify({'code': 400, 'message': '没有音频文件', 'data': None})
    
    audio_file = request.files['audio_file']
    sentence_id = request.form.get('sentence_id')
    
    if not audio_file or not sentence_id:
        return jsonify({'code': 400, 'message': '参数不完整', 'data': None})
    
    result = RecordingController.upload_recording(user_id, sentence_id, audio_file)
    return jsonify(result)

@recordings_bp.route('/audio/<int:recording_id>', methods=['GET'])
def get_audio_file(recording_id):
    file_path = RecordingController.get_audio_file(recording_id)
    
    if not file_path:
        return jsonify({'code': 404, 'message': '文件不存在', 'data': None})
    
    return send_file(file_path, mimetype='audio/wav') 